package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysBook;
import com.ruoyi.system.mapper.SysBookMapper;
import com.ruoyi.system.service.ISysBookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class SysBookServiceImpl implements ISysBookService {
    @Autowired
    private SysBookMapper bookMapper;
    private static final Logger log = LoggerFactory.getLogger(SysBookServiceImpl.class);

    /**
     * 查询所有书籍
     *
     * @return 书籍列表
     */
    @Override
    public List<SysBook> selectBookAll() {
        return bookMapper.selectBookAll();
    }

    @Override
    public List<SysBook> selectBookList(SysBook book) {
        return bookMapper.selectBookList(book);
    }

    /**
     * 新增保存书籍信息
     *
     * @param book 书籍信息
     * @return 结果
     */
    @Override
    public int insertBook(SysBook book) {
        book.setCreateBy(ShiroUtils.getLoginName());
        return bookMapper.insertBook(book);
    }
    /**
     * 批量删除图书信息
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteBookByIds(String ids)
    {
        Long[] bookIds = Convert.toLongArray(ids);
        return bookMapper.deleteBookByIds(bookIds);
    }
    /**
     * 通过图书ID查询图书信息
     *
     * @param bookId 图书ID
     * @return 角色对象信息
     */
    @Override
    public SysBook selectBookById(Long bookId)
    {

        return bookMapper.selectBookById(bookId);
    }


    /**
     * 修改保存图书信息
     *
     * @param book 图书信息
     * @return 结果
     */
    @Override
    public int updateBook(SysBook book)
    {
        book.setUpdateBy(ShiroUtils.getLoginName());
        return bookMapper.updateBook(book);
    }

    /**
     * 导入图书数据
     *
     * @param bookList 图书数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importBook(List<SysBook> bookList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(bookList) || bookList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String loginName = ShiroUtils.getLoginName();
        for (SysBook book : bookList)
        {
            try
            {
                // 验证这个本书是否符合图书名唯一、图书编码唯一
                SysBook bookNameUnique = bookMapper.checkBookNameUnique(book.getBookName());
                SysBook bookCodeUnique = bookMapper.checkBookCodeUnique(book.getBookCode());
                if (StringUtils.isNull(bookNameUnique) && StringUtils.isNull(bookCodeUnique))
                {
                    book.setCreateBy(loginName);
                    bookMapper.insertBook(book);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、图书 " + book.getBookName() + " 导入成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、图书 " + book.getBookName()+"或者ISBN编码"+ book.getBookCode()  + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、图书 " + book.getBookName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 校验图书名称是否唯一
     *
     * @param book 图书信息
     * @return 结果
     */
    @Override
    public boolean checkBookNameUnique(SysBook book)
    {
        Long bookId = StringUtils.isNull(book.getBookId()) ? -1L : book.getBookId();
        SysBook info = bookMapper.checkBookNameUnique(book.getBookName());
        if (StringUtils.isNotNull(info) && info.getBookId().longValue() != bookId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验图书编码是否唯一
     *
     * @param book 图书信息
     * @return 结果
     */
    @Override
    public boolean checkBookCodeUnique(SysBook book)
    {
        Long bookId = StringUtils.isNull(book.getBookId()) ? -1L : book.getBookId();
        SysBook info = bookMapper.checkBookCodeUnique(book.getBookCode());
        if (StringUtils.isNotNull(info) && info.getBookId().longValue() != bookId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

}
